<template>
  <div class="home">
    <div class="login-content">
      <div class="user-image"></div>
      <a-form
        class="login-form"
        name="login-form"
        ref="formRef"
        :model="formState"
        :rules="rules"
        v-bind="layout"
      >
        <a-form-item has-feedback name="userName">
          <a-input
            v-model:value="formState.userName"
            autocomplete="off"
            placeholder="请输入用户名"
            @keyup.enter="onSubmit"
            v-focus
          >
            <template #prefix><UserOutlined style="color: rgba(0, 0, 0, 0.25)" /></template>
          </a-input>
        </a-form-item>
        <a-form-item has-feedback name="pass">
          <a-input-password
            v-model:value="formState.pass"
            type="password"
            autocomplete="off"
            placeholder="请输入密码"
            @keyup.enter="onSubmit"
          >
            <template #prefix><LockOutlined style="color: rgba(0, 0, 0, 0.25)" /></template>
          </a-input-password>
        </a-form-item>
        <a-form-item>
          <a-row type="flex" justify="space-between">
            <a-col :span="12">
              <a-form-item has-feedback name="captcha">
                <a-input
                  v-model:value="formState.captcha"
                  autocomplete="off"
                  placeholder="验证码"
                  @keyup.enter="onSubmit"
                >
                  <template #prefix><LockOutlined style="color: rgba(0, 0, 0, 0.25)" /></template>
                </a-input>
              </a-form-item>
            </a-col>
            <a-col :span="10">
              <img :src="captchaData" alt="" :width="120" :height="40" @click="refreshCaptcha" />
            </a-col>
          </a-row>
        </a-form-item>

        <div class="btn-container">
          <a-button type="primary" @click="onSubmit">提交</a-button>
          <a-button style="margin-left: 10px" @click="resetForm">重置</a-button>
        </div>
      </a-form>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref, UnwrapRef } from 'vue';
import { useRouter } from 'vue-router';
import { UserOutlined, LockOutlined } from '@ant-design/icons-vue';
import { RuleObject, ValidateErrorEntity } from 'ant-design-vue/es/form/interface';
import { HttpResult, getRequest, postRequest } from '@/common/http/http-request';
import { message } from 'ant-design-vue';
import { UserLogin } from '@/api/model-declare';

interface FormState {
  userName: string;
  pass: string;
  captcha: string;
}

export default defineComponent({
  name: 'LoginView',
  components: {
    UserOutlined,
    LockOutlined,
  },
  setup() {
    const router = useRouter();
    const formRef = ref();
    const formState: UnwrapRef<FormState> = reactive({
      userName: '18605128087',
      pass: 'jzt18605128087',
      captcha: '',
    });

    let validateUserName = async (rule: RuleObject, value: string) => {
      if (value === '') {
        return Promise.reject('请输入用户名');
      } else {
        if (value.length < 3 || value.length > 20) {
          return Promise.reject('用户名在3到10位之间');
        }
        return Promise.resolve();
      }
    };

    let validatePass = async (rule: RuleObject, value: string) => {
      if (value === '') {
        return Promise.reject('请输入密码');
      } else {
        if (value.length < 3 || value.length > 20) {
          return Promise.reject('用户名在3到10位之间');
        }
        return Promise.resolve();
      }
    };

    // 表单数据验证
    const rules = {
      userName: [{ validator: validateUserName, trigger: 'blur' }],
      pass: [{ validator: validatePass, trigger: 'blur' }],
      captcha: [
        { required: true, message: '请输入验证码', trigger: 'blur' },
        { min: 4, max: 4, message: '验证码为4位', trigger: 'blur' },
      ],
    };

    // 设置表格布局
    const layout = {
      wrapperCol: { span: 18, offset: 3 },
    };

    //提交数据
    const onSubmit = () => {
      formRef.value
        .validate()
        .then((values: FormState) => {
          postRequest<UserLogin>('/loginapi/admin/login', {
            user_name: values.userName,
            password: values.pass,
            code: values.captcha,
          })
            .then((response: HttpResult<UserLogin>) => {
              // 登录成功保存本地数据，并跳转到主页
              message.success('登录成功!');
              window.localStorage.setItem('TOKEN', response.data.access_token);
              router.push('/home');
            })
            .catch(error => {
              refreshCaptcha();
            });
        })
        .catch((error: ValidateErrorEntity<FormState>) => {
          console.log('error', error);
        });
    };

    // 重置表单
    const resetForm = () => {
      formRef.value.resetFields();
    };

    //图形验证码Ç
    let captchaData = ref('');
    let refreshCaptcha = () => {
      getRequest<string>('/loginapi/captcha').then((response: HttpResult<string>) => {
        captchaData.value = response.data;
      });
    };
    refreshCaptcha();

    return {
      formRef,
      formState,
      rules,
      layout,
      onSubmit,
      resetForm,
      captchaData,
      refreshCaptcha,
    };
  },
});
</script>

<style lang="scss" scoped>
.home {
  position: relative;
  width: 100%;
  height: 100%;
  background-color: #1f4a69;

  .login-content {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 450px;
    height: 320px;
    background-color: #fcfefc;
    border-radius: $border-radius-value;

    .user-image {
      position: absolute;
      left: 50%;
      transform: translate(-50%, -50%);
      width: 100px;
      height: 100px;
      border-radius: 50%;
      border: 8px white solid;
      box-shadow: 0px 0px 10px #888888;
      background-color: #eceeec;
      background-size: contain;
      background-image: url(~@/assets/logo.png);
    }
  }

  .login-form {
    position: absolute;
    top: 60px;
    width: 100%;
    padding: 0 20px;
    box-sizing: border-box;
  }
  .btn-container {
    display: flex;
    flex-direction: row;
    justify-content: flex-end;
  }
}
</style>
